﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace SharpGameLibrary
{
    public static class WorldMap
    {
        static Dictionary<int, Map> maps = new Dictionary<int, Map>();
        static Dictionary<string, Tileset> tilesets = new Dictionary<string, Tileset>();

        static WorldMapData datas = new WorldMapData();

        public static Map getMap(int index)
        {
            return WorldMap.maps[index];
        }

        public static Dictionary<int, Map> getMapsDictionary()
        {
            return WorldMap.maps;
        }

        public static List<Map> getMaps()
        {
            return new List<Map>(WorldMap.maps.Values);
        }

        public static List<int> getMapsId()
        {
            return new List<int>(WorldMap.maps.Keys);
        }

        public static void addMap(Map map)
        {
            WorldMap.maps.Add(map.Index, map);
        }

        public static Tileset getTileset(string name)
        {
            return WorldMap.tilesets[name];
        }

        public static void addTileset(string name, Tileset tileset)
        {
            WorldMap.tilesets.Add(name, tileset);
        }

        #region Save / Load

        static public void save(FileStream fs)
        {
            WorldMap.datas.store();

            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(fs, WorldMap.datas);
        }

        static public void load(FileStream fs, bool isOnEditor)
        {
            BinaryFormatter formatter = new BinaryFormatter();

            WorldMap.datas = (WorldMapData)formatter.Deserialize(fs);

            foreach (int key in WorldMap.datas.Ids)
                WorldMap.maps.Add(key, new Map(key));
        }

        #endregion

        #region Data

        [Serializable]
        private class WorldMapData
        {
            int[] ids;

            public int[] Ids
            {
                get
                {
                    return this.ids;
                }
            }

            public WorldMapData()
            {
            }

            public void store()
            {
                this.ids = new int[WorldMap.maps.Count];
                WorldMap.maps.Keys.CopyTo(this.ids, 0);
            }
        }

        #endregion
    }
}
